package cn.play.cardgame;

import android.app.Application;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;

import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechUtility;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.cookie.CookieJarImpl;
import com.zhy.http.okhttp.cookie.store.PersistentCookieStore;
import com.zhy.http.okhttp.https.HttpsUtils;
import com.zhy.http.okhttp.log.LoggerInterceptor;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MyApplication extends Application {
	private String CER_12306 = "-----BEGIN CERTIFICATE-----\n"
			+ "MIICmjCCAgOgAwIBAgIIbyZr5/jKH6QwDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UEBhMCQ04xKTAn\n"
			+ "BgNVBAoTIFNpbm9yYWlsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRTUkNBMB4X\n"
			+ "DTA5MDUyNTA2NTYwMFoXDTI5MDUyMDA2NTYwMFowRzELMAkGA1UEBhMCQ04xKTAnBgNVBAoTIFNp\n"
			+ "bm9yYWlsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRTUkNBMIGfMA0GCSqGSIb3\n"
			+ "DQEBAQUAA4GNADCBiQKBgQDMpbNeb34p0GvLkZ6t72/OOba4mX2K/eZRWFfnuk8e5jKDH+9BgCb2\n"
			+ "9bSotqPqTbxXWPxIOz8EjyUO3bfR5pQ8ovNTOlks2rS5BdMhoi4sUjCKi5ELiqtyww/XgY5iFqv6\n"
			+ "D4Pw9QvOUcdRVSbPWo1DwMmH75It6pk/rARIFHEjWwIDAQABo4GOMIGLMB8GA1UdIwQYMBaAFHle\n"
			+ "tne34lKDQ+3HUYhMY4UsAENYMAwGA1UdEwQFMAMBAf8wLgYDVR0fBCcwJTAjoCGgH4YdaHR0cDov\n"
			+ "LzE5Mi4xNjguOS4xNDkvY3JsMS5jcmwwCwYDVR0PBAQDAgH+MB0GA1UdDgQWBBR5XrZ3t+JSg0Pt\n"
			+ "x1GITGOFLABDWDANBgkqhkiG9w0BAQUFAAOBgQDGrAm2U/of1LbOnG2bnnQtgcVaBXiVJF8LKPaV\n"
			+ "23XQ96HU8xfgSZMJS6U00WHAI7zp0q208RSUft9wDq9ee///VOhzR6Tebg9QfyPSohkBrhXQenvQ\n"
			+ "og555S+C3eJAAVeNCTeMS3N/M5hzBRJAoffn3qoYdAO1Q8bTguOi+2849A==\n"
			+ "-----END CERTIFICATE-----";

	public static MyApplication myApplication;

	public static MyApplication getContext() {
		return myApplication;
	}

	@Override
	public void onCreate() {
		super.onCreate();

		myApplication = this;
//		Context context = getApplicationContext();
//		// 获取当前包名
//		String packageName = context.getPackageName();
//		// 获取当前进程名
//		String processName = getProcessName(android.os.Process.myPid());
//		// 设置是否为上报进程
//		UserStrategy strategy = new UserStrategy(context);
//		strategy.setUploadProcess(processName == null || processName.equals(packageName));
//		CrashReport.initCrashReport(getApplicationContext(), "8a33f3e364", true,strategy); 

		SpeechUtility.createUtility(this, SpeechConstant.APPID + "=59534fcd");
		initClient();

		CrashHandler crashHandler = CrashHandler.getInstance();
		crashHandler.init(getApplicationContext());
	}

	/**
	 * 获取进程号对应的进程名
	 *
	 * @param pid 进程号
	 * @return 进程名
	 */
	private static String getProcessName(int pid) {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
			String processName = reader.readLine();
			if (!TextUtils.isEmpty(processName)) {
				processName = processName.trim();
			}
			return processName;
		} catch (Throwable throwable) {
			throwable.printStackTrace();
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException exception) {
				exception.printStackTrace();
			}
		}
		return null;
	}

	private void initClient() {
		// 设置缓存目录
		File cacheDirectory = new File(getCacheDir().getAbsolutePath(),
				"CardGameCache");
		Cache cache = new Cache(cacheDirectory, 10 * 1024 * 1024);

		try {
			HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(
					null, null, null);
			/**
			 * 设置具体的证书 HttpsUtils.SSLParams sslParams =
			 * HttpsUtils.getSslSocketFactory( new InputStream[] {
			 * getAssets().open("srca.cer") }, null,null); HttpsUtils.SSLParams
			 * sslParams = HttpsUtils.getSslSocketFactory( new InputStream[] {
			 * new Buffer().writeUtf8(CER_12306).inputStream()}, null, null);
			 *
			 * 双向认证
			 * HttpsUtils.getSslSocketFactory(证书的inputstream,本地证书的inputstream,
			 * 本地证书的密码)
			 * */

			/**
			 *
			 PersistentCookieStore //持久化cookie SerializableHttpCookie
			 * //持久化cookie MemoryCookieStore //cookie信息存在内存中
			 *
			 * */
			CookieJarImpl cookieJar1 = new CookieJarImpl(
					new PersistentCookieStore(this));
			OkHttpClient okHttpClient = new OkHttpClient.Builder()
					.connectTimeout(10000L, TimeUnit.MILLISECONDS)
					.readTimeout(10000L, TimeUnit.MILLISECONDS)
					.addInterceptor(new LoggerInterceptor("CardGame"))
					.cookieJar(cookieJar1).cache(cache)
							// 添加拦截器
							// .addInterceptor(new MyIntercepter())
					.hostnameVerifier(new HostnameVerifier() {
						@Override
						public boolean verify(String hostname,
											  SSLSession session) {
							return true;
						}
					}).sslSocketFactory(sslParams.sSLSocketFactory).build();
			OkHttpUtils.initClient(okHttpClient);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 拦截器
	 */
	private class MyIntercepter implements Interceptor {
		@Override
		public Response intercept(Chain chain) throws IOException {
			Request request = chain.request();
			if (!isNetworkReachable(MyApplication.this)) {
				request = request.newBuilder()
						.cacheControl(CacheControl.FORCE_CACHE)// 无网络时只从缓存中读取
						.build();
			}

			Response response = chain.proceed(request);
			if (isNetworkReachable(MyApplication.this)) {
				int maxAge = 60 * 60; // 有网络时 设置缓存超时时间1个小时
				response.newBuilder().removeHeader("Pragma")
						.header("Cache-Control", "public, max-age=" + maxAge)
						.build();
			} else {
				int maxStale = 60 * 60 * 24 * 28; // 无网络时，设置超时为4周
				response.newBuilder()
						.removeHeader("Pragma")
						.header("Cache-Control",
								"public, only-if-cached, max-stale=" + maxStale)
						.build();
			}
			return response;
		}
	}

	/**
	 * 判断网络是否可用
	 *
	 * @param context
	 *            Context对象
	 */
	public Boolean isNetworkReachable(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo current = cm.getActiveNetworkInfo();
		if (current == null) {
			return false;
		}
		return (current.isAvailable());
	}

}
